<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 
  通过Object.defineProperty劫持数据发生的改变
  如果数据改变，在set进行赋值，触发update方法
  进行更新节点内容，从而实现数据双向绑定 
  -->
</head>

<body>
  <div id="app">
    <button @click="btn">修改msg</button>
    <p>{{msg}}</p>
    <button @click="add">增加count</button>
    <p>{{count}}</p>
    <button @click="xiugaiArray">修改数组</button>
    <p>{{arr}}</p>
    <button @click="xiugaiObj">obj修改某个属性</button>
    <button @click="addObjAttr">obj添加属性</button>
    <p>{{obj.person.name}}</p>
    <p>{{obj.animal}}</p>
    <input type="text" v-model="inputModel">
    {{inputModel}}
    <p>使用computed {{msgComputed}}</p>
    <input type="text" v-model="msg">
    <p>{{msgWatch}}</p>
  </div>
</body>

<script src="./手写Vue2.js"></script>

<script>

  const vm = new Vue({
    el: '#app',
    data: {
      msg: 'hello vue2',
      msgWatch: 'msgWatch',
      count: 100,
      arr: [1, 2, 3],
      obj: {
        person: {
          name: 'hhh'
        },
        animal: {
          dog: {
            name: '小狗'
          }
        }
      },
      inputModel: '请输入'
    },
    beforeCreate() {
      // console.log('beforeCreate',this.$data,this.$el)
    },
    created() {
      // console.log('created',this.$data,this.$el)
    },
    beforeMount() {
      // console.log('beforeMount',this.$data,this.$el)
    },
    mounted() {
      // console.log('mounted',this.$data,this.$el)
    },
    computed: {
      msgComputed() {
        console.log(this.msg + ' computed');

        return this.msg + ' computed'
      }
    },
    watch: {
      // 'msg': {
      //   handler(newVal, oldVal) {
      //     this.msgWatch = this.msg + ' watch'
      //   },
      //   immediate: true
      // },
      msg(newVal, oldVal) {
        this.msgWatch = this.msg + ' watch'
      },
      'obj': {
        handler(newVal, oldVal) {
          console.log(newVal);

          this.obj = this.obj + ' watch'
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      add() {
        this.count += 1
      },
      btn(e) {
        this.msg = 'welcome vue2 双向绑定'
      },
      xiugaiArray() {
        // this.arr[0] = 9
        this.arr = [3, 6, 9]
        console.log(this.arr);
      },
      xiugaiObj() {
        // this.obj.person.name = 'luo'
        this.obj = {
          person: {
            name: 'luo'
          },
          animal: {
            dog: {
              name: '小哈'
            }
          }
        }
      },
      addObjAttr() {
        this.obj.animal.dog.color = 'black'
        // console.log(this);
      }
    },
  })



</script>

</html>